<template>
    <div>
        <table>
            <thead>
                <tr>
                    <th>编号</th>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>成绩</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(item,index) in students" :key="item.id">
                    <td>{{item.id}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.age}}</td>
                    <td>
                       <input type="text" v-model="item.score" v-if="item.isEdit" ref="inputRef">
                       <span v-else>{{item.score}}</span> 
                    </td>
                    <td>
                        <button v-if="item.isEdit" @click="confirm(index)">确认</button>
                        <button v-else @click="modify(index)">修改</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
export default {
    data(){
        return{
            students:[
                {id:'1001',name:'宋敏',age:18,score:80,isEdit:false},
                {id:'1002',name:'孙伟',age:22,score:81,isEdit:false},
                {id:'1003',name:'刘可欣',age:23,score:82,isEdit:false},
            ]
            
        }
    },
    methods:{
        modify(index){
           this.students[index].isEdit=true
           //将文本变成input框，由于vue的异步更新，数据变化后，不会立即更新页面的DOM
           //nextTick就是为了在同一个事件处理中，如果数据变化了，然后获取到页面更新后的DOM元素
            this.$nextTick(()=>{
              if(this.$refs.inputRef.length==1){
                this.$refs.inputRef[0].focus()
              }else{
                this.$refs.inputRef[this.$refs.inputRef.length-1].focus()
              }
           })
        },
        confirm(index){
            this.students[index].isEdit=false

        }
    }
}
</script>

<style>

</style>